package com.tony.mindhr.service;

import com.tony.mindhr.mapper.MenuMapper;
import com.tony.mindhr.mapper.MenuRoleMapper;
import com.tony.mindhr.model.Hr;
import com.tony.mindhr.model.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: MenuService
 * @Auther: 皮蛋布丁
 * @Date: 2021/05/12/22:05
 * @Description:
 */
@Service
public class MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    MenuRoleMapper menuRoleMapper;

    public List<Menu> getMenuByHrId() {
        //getPrincipal:当前登录的用户对象
        return menuMapper.getMenuByHrId(((Hr) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
    }

    //@Cacheable:添加缓存，避免每次都要查询一次(需要配套Redis使用)
    //@Cacheable
    public List<Menu> getAllMenusWithRole() {
        return menuMapper.getAllMenusWithRole();
    }

    /**
    * @Description: getAllMenus 获取菜单树
    * @Param: []
    * @return: java.util.List<com.tony.mindhr.model.Menu>
    * @Author: 皮蛋布丁
    * @Date: 2021/6/3 19:50
    */
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }

    /**
    * @Description: getMidsByRid 根据用户id获取菜单id
    * @Param: [rid]
    * @return: java.util.List<java.lang.Integer>
    * @Author: 皮蛋布丁
    * @Date: 2021/6/3 20:27
    */
    public List<Integer> getMidsByRid(Integer rid) {
        return menuMapper.getMidsByRid(rid);
    }

    /**
    * @Description: updateMenuRole 根据用户id修改菜单(先将原有的删除，再插入新的)
    * @Param: [rid, mids]
    * @return: boolean
    * @Author: 皮蛋布丁
    * @Date: 2021/6/3 21:04
    */
//    添加事务
    @Transactional
    public boolean updateMenuRole(Integer rid, Integer[] mids) {
        //先删除原有数据
        menuRoleMapper.deleteByRid(rid);
        //解决角色置空问题
        if (mids == null || mids.length == 0) {
            return true;
        }
        //再添加新的数据
        Integer result = menuRoleMapper.insertRecord(rid,mids);
        return result == mids.length;
    }
}
